package cn.jisol.ngame.network.websocket;

import cn.jisol.ngame.actions.frame.SNFrameSyncAction;
import cn.jisol.ngame.actions.frame.client.NFrameSyncClient;
import cn.jisol.ngame.actions.statesync.SNStateSyncAction;
import cn.jisol.ngame.proto.message.NGameMessageOuterClass;
import cn.jisol.ngame.util.spring.SpringBeanUtils;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.Session;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Getter
public class WebFrameSyncSocket {
    
    public static final Map<String, NFrameSyncClient> CLIENTS = new ConcurrentHashMap<>();
    
    SNFrameSyncAction SN_StateSync;
    
    public void onOpen(Session session, NFrameSyncClient nClient){
        
        if (Objects.isNull(SN_StateSync)){
            SN_StateSync = SpringBeanUtils.getBean(SNFrameSyncAction.class);
            SN_StateSync.clients = WebFrameSyncSocket.CLIENTS;
        }
    
        SN_StateSync.clients = CLIENTS;
        System.out.println("[" + nClient.getUuid() + "] 加入...");
        CLIENTS.put(session.getId(),nClient);
        
    }
    
    public SNFrameSyncAction getAction(){
        if (Objects.isNull(SN_StateSync)){
            SN_StateSync = SpringBeanUtils.getBean(SNFrameSyncAction.class);
            SN_StateSync.clients = CLIENTS;
        }
        return SN_StateSync;
    }
    
    //开始帧同步
    public void nStart(){
        this.nEnd();
        this.getAction().nGameSyncStart();
    }
    
    //关闭帧同步
    public void nEnd(){
        if(Objects.nonNull(this.getAction().nSyncFPSMode) && this.getAction().nSyncFPSMode.getIsExecute()){
            this.getAction().nSyncFPSMode.end();
            this.getAction().nSyncFPSMode = null;
        }
    }
    
    public void onMessage(Session session, NGameMessageOuterClass.NGameMessage message){
    
        NFrameSyncClient nClient = CLIENTS.get(session.getId());
        if(Objects.nonNull(nClient)) nClient.onMessage(message);
        
    }
    
    
    public void onClose(Session session){
        CLIENTS.remove(session.getId());
    }
}
